package thread;

public class SyDemo1 {
    static boolean p1;
    static boolean p2;

    public static void main(String[] args) {
        Bank bank = new Bank();
        int a = 1;
        while (true) {
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    p1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread() {
                @Override
                public void run() {
                    p2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            try {
                Thread.sleep(50);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            if (p1&& p2) {
                System.out.println("error");
                System.out.println(a);
                break;
            } else {
                ++a;
                p1=false;
                p2=false;
                bank.setAccount(20000);
            }
        }
    }
}

class Bank {
    private int account = 20000;

    public synchronized boolean getMoney(int money) {
        int account = getAccount();
        if (account >= money) {
            account = account - money;
            Thread.yield();
            setAccount(account);
            return true;
        }
        return false;
    }

    public int getAccount() {
        return account;
    }

    public void setAccount(int x) {
        this.account = x;
    }
}